/*
 * Displays the UI and updates the google map with everyone's positioning.
 * Receives updated location data from StalkernetService which it uses to update the map.
 */

package com.stalkernet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.urbanairship.push.AirMail;

public class StalkernetManager extends MapActivity
{
    /** Called when the activity is first created. */
	
	private int PICK_CONTACT = 0;
	
	protected static boolean am_register = true;
    MapView mapView;
    MapController mc;
    GeoPoint p;
    Location curLoc;
    BroadcastReceiver meBroad, friendBroad;
    List<Overlay> mapOverlays;
    MapOverlay itemizedoverlay;
    HashMap<String,Location> friends=new HashMap<String,Location>();
    Context context=this;
    
    private ArrayList<String> phoneNumbersToSend = new ArrayList<String>();
    
	private void startStalkernetService() {
		Intent i = new Intent(this, StalkernetService.class);
		startService(i);
		registerReceiver(meBroad, new IntentFilter(StalkernetService.broadcastIntentString));
		registerReceiver(friendBroad, new IntentFilter(StalkernetService.friendBroadcast));
	}
	private void stopStalkernetService()
	{
		stopService(new Intent(this, StalkernetService.class));
		unregisterReceiver(meBroad);
		unregisterReceiver(friendBroad);
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.stalkernet_manager_menu, menu);
		return true;
	}
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.simLocUpdate:
			Log.d("MGR", "item1 selected");
			StalkernetBase.d("simulate button clicked");
			Intent i=new Intent(StalkernetService.friendBroadcast);
			HashMap<String,Location> h=new HashMap<String,Location>();
			Location l=new Location("");
			double latitude = 40.748232;
			double longitude = -73.995838;
			l.setLatitude(latitude);
			l.setLongitude(longitude);
			h.put("Josh",l);
			
			Location l2=new Location("");
			latitude = 40.754409;
			longitude = -73.976612;
			l2.setLatitude(latitude);
			l2.setLongitude(longitude);
			h.put("Oliver",l2);
			i.putExtra("friendLoc", h);
			sendBroadcast(i);
		}
		return super.onMenuItemSelected(featureId, item);

	}

	
	
	
	/*
	 * Takes username as a string, posts it along with the apid (string). 
	 * returns the userid as an int
	 */
	void sendLoginRequest(String username, int roomID) {
		StalkernetBase.t(this, "sendLoginRequest "+username+"\t"+Stalkernet.getAPID() );
		
		String urlString = "http://astar.xvm.mit.edu/login/";
		urlString += username;
		urlString += "/";
		urlString += Stalkernet.getAPID();
		urlString += "/";
		urlString += Stalkernet.getRoomid();
		
		
		

		StringBuilder response = new StringBuilder();
		StalkernetBase.d("sendLoginRequest", "url is:" + urlString);
		StalkernetBase.t(this, "sendLoginRequest url is:" + urlString);
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpURLConnection httpconn;
	
		try {
			httpconn = (HttpURLConnection) url.openConnection();

			if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader input = new BufferedReader(
						new InputStreamReader(httpconn.getInputStream()), 8192);
				String strLine = null;
				while ((strLine = input.readLine()) != null) {
					response.append(strLine);
					StalkernetBase.t(this,"strline="+strLine);

				}
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if( Stalkernet.getRoomid() == -1 )
		{
			
			StalkernetBase.t(this,"getroomid==-1");
		StalkernetBase.d("sendLoginRequest", "response.toString="+response.toString());
		StringTokenizer stk = new StringTokenizer(response.toString(), ",");

		Stalkernet.setUserid(Integer.parseInt(stk.nextToken()));
		Stalkernet.setRoomid(Integer.parseInt(stk.nextToken()));
		}
		
	}

	public void updateMap()
	{
		int left=0, right=0, up=0, down=0;
		for(String s:friends.keySet())
		{
			Location tloc=friends.get(s);
            int lat=(int)(tloc.getLatitude()*1E6);
            int lon=(int)(tloc.getLongitude()*1E6);
			GeoPoint gp=new GeoPoint(lat,lon);
            if(left==0||lat<left) left=lat;
            if(right==0||lat>right) right=lat;
            if(up==0||lon>up) up=lon;
            if(down==0||lon<down) down=lon;
            OverlayItem overlayitem = new OverlayItem(gp,s, "Hey what's up!");
            itemizedoverlay.addOverlay(overlayitem);
        }
        mc.animateTo(new GeoPoint((left+right)/2,(up+down)/2));
        StalkernetBase.d("stalk "+Math.max(right-left,down-up));
        //mc.setZoom(21-(int)(.6*Math.log(1+Math.max(right-left,down-up))));
	}
	
	private void findCenter()
	{
		double lat=0, lon=0;
		for(String s:friends.keySet())
		{
			Location l=friends.get(s);
			lat+=l.getLatitude();
			lon+=l.getLongitude();
		}
		lat/=friends.size();
		lon/=friends.size();
	}

	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stalkernet_manager);
        

        Intent i = getIntent();
        Uri uri = i.getData();
        if (uri !=null)
        {
        	List<String> list = uri.getPathSegments();
        	  	StalkernetBase.t(this, list.toString());
        	Stalkernet.setRoomid(Integer.parseInt(list.get(1)));
        	((EditText) findViewById(R.id.Username)).setText("guest");
        }
        
        
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mc = mapView.getController();


        ( (Button) findViewById(R.id.invite_friend)).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addContact();
			}

			
		});
              
        mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        itemizedoverlay = new MapOverlay(drawable,this);
        mapOverlays.add(itemizedoverlay);
        

        if(am_register){
            AirMail am = AirMail.getInstance();
            am.register(this);
        }
        
        meBroad = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
            	friends.put("Me",(Location)intent.getParcelableExtra("myLoc"));
                updateMap();
            }
        };
        
        friendBroad = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    			HashMap<String,Location> tempMap=(HashMap<String,Location>)intent.getSerializableExtra("friendLoc");
    			//find the extreme points
    			for(String s:tempMap.keySet())
    				friends.put(s,tempMap.get(s));
    			updateMap();
            }
        };
			
((Button) findViewById(R.id.places))
.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View view) {
		findCenter();
		Intent inte=new Intent(context, YelpSearch.class);
		inte.putExtra("friends",friends);
		startActivity(inte);
	}
});

( (Button) findViewById(R.id.createRoom)).setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		sendLoginRequest( ((EditText) findViewById(R.id.Username)).getText().toString(), Stalkernet.getRoomid()) ;
        startStalkernetService();      
		Thread thread = new UserPoller(friends,Stalkernet.getUserid(),StalkernetManager.this);
		thread.start();
	}

	
});
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopStalkernetService();
	}
	
	public void addContact() {

		//Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
		
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        
		startActivityForResult(intent, PICK_CONTACT);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {

		String number = null;
		  if (requestCode == PICK_CONTACT)
		  {         
			  if (intent != null) {
			        Uri uri = intent.getData();

			        if (uri != null) {
			            Cursor c = null;
			            try {
			                c = getContentResolver().query(uri, new String[]{ 
			                            ContactsContract.CommonDataKinds.Phone.NUMBER,  
			                            ContactsContract.CommonDataKinds.Phone.TYPE },
			                        null, null, null);

			                if (c != null && c.moveToFirst()) {
			                     number = c.getString(0);
			                    int type = c.getInt(1);
			                    //showSelectedNumber(type, number);
			                }
			            } finally {
			                if (c != null) {
			                    c.close();
			                }
			            }
			        }
			    }

	
		      Toast.makeText(this, "Contect LIST  =   "+number, Toast.LENGTH_LONG).show();
		      sendTextNumber(number);
		  }

	}// onActivityResult

	void sendTextNumber(String phoneNumber) {
		StalkernetBase.t(this, "sendTextNumber "+phoneNumber+"\t"+Stalkernet.getUserid() );
		
		String urlString = "http://astar.xvm.mit.edu/text/";
		urlString += Stalkernet.getUserid();
		urlString += "/";
		urlString += phoneNumber;
		
		StringBuilder response = new StringBuilder();
		StalkernetBase.d("sendTextNumber", "url is:" + urlString);
		StalkernetBase.t(this, "sendTextNumber url is:" + urlString);
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpURLConnection httpconn;

		try {
			httpconn = (HttpURLConnection) url.openConnection();

			if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader input = new BufferedReader(
						new InputStreamReader(httpconn.getInputStream()), 8192);
				String strLine = null;
				while ((strLine = input.readLine()) != null) {
					response.append(strLine);
				}
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		StalkernetBase.d("ERRORMESSAGE: HTTPREQUEST",response.toString());	
		
	}
}